package haois.Interceptor;

import haois.constant.NetworkUtil;
import haois.constant.StatusCode;
import haois.exception.ErrorException;
import haois.module.rbac.daoman.Manager;
import haois.security.HandleCookie;
import haois.security.HandleToken;
import haois.module.rbac.service.ManagerService;
import haois.util.DateUtil;
import org.apache.catalina.connector.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * Created by haol on 2017/4/1.
 * 判断操作的组织自己是否为管理员
 */
@Repository
public class ManagerInterceptor extends HandlerInterceptorAdapter {

    private ManagerService managerService;

    public ManagerInterceptor(ManagerService managerService) {
        this.managerService = managerService;
    }

    Logger logger = LoggerFactory.getLogger(ManagerInterceptor.class);
    HandleToken handleToken = new HandleToken();


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        //logger.info("进入验证WEB Login拦截器");
        try {
            String token = HandleCookie.getValueByName(request, StatusCode.COOKIE_JWT_WEB);
            handleToken.analyzeJWT(token);
            String account = handleToken.getValueByKey(token, StatusCode.SUBJECT_KEY_ACCOUNT);
            logger.debug("管理员[{}]的访问路径为-->{}", account, request.getRequestURI());
            Date date = handleToken.getIssuedAt(token);

            Manager manager = managerService.getByAccount(account);

            if (date.getTime() != manager.getLoginTime().getTime()) {
                logger.error("管理员[{}]当前的IP地址为[{}],本地登录时间为[{}],[{}]已在其他地方登录",
                        manager.getAccount(), NetworkUtil.getIpAddress(request),
                        DateUtil.getYMdHms(date), DateUtil.getYMdHms(new Date(manager.getLoginTime().getTime())));
//                response.setStatus(Response.SC_FORBIDDEN);
//                throw new ErrorException(ReturnState.CODE_13, "该用户已在其他地方登录过，请重新登录");
            }
            String subject = handleToken.getSubject(token);
            HandleCookie.updateCookie(subject, response, handleToken.getIssuedAt(token), StatusCode.COOKIE_JWT_WEB);
            return true;
            //重新成token
        } catch (NullPointerException e) {
            response.setStatus(Response.SC_FORBIDDEN);
            throw new ErrorException("13", "当前用户信息不存在，请重新登录");
        } catch (Exception e) {
            response.setStatus(Response.SC_FORBIDDEN);
            throw new ErrorException("13", e.getMessage());
        }
    }
}
